<template>
  <div>
    <el-upload
      :action="`${path}/fileUploadAndDownload/upload`"
      :before-upload="checkFile"
      :headers="{ 'x-hyxxkj-token': userStore.token }"
      :on-error="uploadError"
      :on-success="uploadSuccess"
      :show-file-list="false"
      list-type="picture-card"
      class="upload-btn"
    >
     <CustomPic v-if="imageUrl" pic-type="file" :pic-src="imageUrl" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
</template>

<script setup>

import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/pinia/modules/user'
import CustomPic from '@/components/customPic/index.vue'
const props = defineProps({
  imageUrl: {
    type: String,
    required: false,
    default: ''
  }
})
const emit = defineEmits(['on-success'])
const path = ref(import.meta.env.VITE_BASE_API)
const userStore = useUserStore()
const fullscreenLoading = ref(false)

const checkFile = (file) => {
  fullscreenLoading.value = true
  const isJPG = file.type === 'image/jpeg'
  const isPng = file.type === 'image/png'
  const isGif = file.type === 'image/gif'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG && !isPng && !isGif) {
    ElMessage.error('上传图片只能是 jpg、png、gif 格式!')
    fullscreenLoading.value = false
    return false
  }
  if (!isLt2M) {
    ElMessage.error('未压缩的上传图片大小不能超过 2M，请使用压缩上传')
    fullscreenLoading.value = false
    return false
  }
  return (isPng || isJPG) && isLt2M
}

const uploadSuccess = (res) => {
  const { data } = res
  if (data.file) {
     props.imageUrl =data.file.url
    emit('on-success', data.file.url)
  }
}

const uploadError = () => {
  ElMessage({
    type: 'error',
    message: '上传失败'
  })
  fullscreenLoading.value = false
}

</script>

<script>

export default {
  name: 'UploadCommon',
  methods: {

  }
}
</script>
